// Rong Xue
// CPE 301 DA6
// April 15 2014
//////////////////////////////////////////////////

// include necessary libraries
#define F_CPU 1000000UL
#include <util/delay.h>
#include <avr/io.h>

uint16_t getADC(void)
// Function for getting the ADC value and return it back to the call function
// the value is come from the PORTC 0.
{
	ADCSRA |=(1<<ADSC);
	while((ADCSRA&(1<<ADIF))==0);
	return ADC;
}
void delay_ms(uint16_t count)
// Function for delay, _delay_ms() can only store value
{
	while(count--) {
		_delay_ms(1);

	}
}

void runstepper( int t)
// Function for stepper moter which the delay will depends on the pvalue
{
	uint16_t dt;
	dt=t*5;
	PORTB =0x01;
	delay_ms(dt);
	PORTB =0x02;
	delay_ms(dt);
	PORTB =0x04;
	delay_ms(dt);
	PORTB =0x08;
	delay_ms(dt);
}

void runservo( int t)
// Function for the stepper moter which the rolation will depends on the pvalue
{
	OCR1A = 59*t;
}


int main(void)
{
	uint16_t pvalue; // declaration of pvaleu, the value to control the motors
	
	int a=8000; // declaration of a value=8000;
	int t; // declaration of t value use for the motor control
	DDRD|=(1<<PD1); // set port d1  as output signal for servo motor
	DDRB = 0xFF;    // set port b as output signal for stepper motor
	DDRC = 0x00;    // set port C as control port
	// Stepper model initialization
	ADMUX|=(1<<REFS0)|(1<<ADLAR);
	ADCSRA|=(1<<ADPS0)|(1<<ADPS1)|(1<<ADPS2)|(1<<ADEN);
	// Servo motor command initialization
	ICR1=2000;
	TCCR1A|=(1<<WGM11)|(1<<COM1A1);
	TCCR1B|=(1<<CS11)|(1<<WGM12)|(1<<WGM13);

	while(1){
		pvalue=getADC(); // get the pot value
		for( t=1; pvalue<a; t++) // compare the pot value with and calculate the t value
		a=a*t;
		runstepper(t); // send the t value to run the stepper motor
		runservo(t); // send the t value to run the servo motor
	}

}
